//
//  DHS2_MessageViewController.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/6/7.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHS2_MessageViewController.h"
#import "DHS2_MessageCell.h"

@interface DHS2_MessageViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *arr;
@property (strong, nonatomic) NSMutableArray *tableViewArr;
@property (weak, nonatomic) IBOutlet UIView *tabView;
@property (strong, nonatomic) NSArray *typeArr;

@property (assign, nonatomic) NSInteger currentTypeIndex;

@property (strong, nonatomic) UIView *lineView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayout;

@end

@implementation DHS2_MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.titleLabel.text = @"通知";
    
    UIButton *doneButton = [[UIButton alloc] initWithFrame:CGRectMake(self.navView.width - 74, self.navView.height - 44, 64, 44)];
    [doneButton setTitle:@"全部已读" forState:UIControlStateNormal];
    doneButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [doneButton setTitleColor:[UIColor colorWithHexString:@"#4a4a4a"] forState:UIControlStateNormal];
    [self.navView addSubview:doneButton];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DHS2_MessageCell" bundle:nil] forCellReuseIdentifier:kDHS2_MessageCell];
    self.tableView.mj_header = [DHMJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadMessage)];
    self.tableView.mj_footer = [DHMJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreMessage)];
    
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
    
    self.currentTypeIndex = 0;
    
    if ([Login isLogin]) {
        [self loadType];
    }
}

- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)loadType{
    [[DHNetAPIClient shareDHNetAPIClient] request_user_notification_typesWithParams:@{} andBlock:^(id data, NSError *error) {
        self.typeArr = [data objectForKey:@"types"];
        CGFloat width = kScreenWidth / (self.typeArr.count + 1);
        
        UIButton *buttonAll = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, width, self.tabView.height)];
        [buttonAll setTitle:@"全部" forState:UIControlStateNormal];
        [buttonAll.titleLabel setFont:[UIFont fontWithName:@"STHeitiSC-Medium" size:15]];
        [buttonAll setTitleColor:[UIColor colorWithHexString:@"#575757"] forState:UIControlStateNormal];
        buttonAll.tag = 0;
        [buttonAll addTarget:self action:@selector(tabAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.tabView addSubview:buttonAll];
        
        [self.typeArr enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake((idx + 1) * width, 0, width, self.tabView.height)];
            [button setTitle:[NSString stringWithFormat:@" %@",obj] forState:UIControlStateNormal];
            [button.titleLabel setFont:[UIFont fontWithName:@"STHeitiSC-Medium" size:15]];
            [button setTitleColor:[UIColor colorWithHexString:@"#575757"] forState:UIControlStateNormal];
            button.tag = (idx + 1);
            [button addTarget:self action:@selector(tabAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.tabView addSubview:button];
            
            if ([Login isLogin]) {
                [self loadMessage];
            }
        }];
        
        
        
        if (!self.lineView) {
            self.lineView = [[UIView alloc] initWithFrame:CGRectMake(0, self.tabView.bottom - 2, width / 2, 2)];
            self.lineView.backgroundColor = [UIColor colorWithHexString:@"#414141"];
            [self.view addSubview:self.lineView];
            self.lineView.centerX = width / 2;
        }
    }];
}

- (void)loadMessage{
    if ([Login isLogin]) {
        [[DHNetAPIClient shareDHNetAPIClient] request_user_notificationsWithParams:@{} andBlock:^(id data, NSError *error) {
            [self.tableView.mj_header endRefreshing];
            if (data) {
                self.arr = [data objectForKey:@"notifications"];
                [self filterArr:self.typeArr[self.currentTypeIndex]];
                [self showTabRed];
            }
        }];
    }else{
        [self.tableView.mj_header endRefreshing];
    }
}

- (void)loadMoreMessage{
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
}

- (void)showTabRed{
    NSArray *buttonArr = self.tabView.subviews;
    
    [self.arr enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        for (UIButton *btn in buttonArr) {
            NSString *btnTitle = btn.titleLabel.text;
            btnTitle = [btnTitle stringByReplacingOccurrencesOfString:@" " withString:@""];
            if (![[obj objectForKey:@"read"] boolValue] && [btnTitle isEqualToString:[obj objectForKey:@"type"]]) {
                [btn setImage:[UIImage imageNamed:@"red"] forState:UIControlStateNormal];
            }
        }
    }];
}

- (void)dealloc
{
    NSLog(@"销毁");
}

- (IBAction)allReadAction:(id)sender {
    [[DHNetAPIClient shareDHNetAPIClient] request_notifications_readallWithParams:@{} andBlock:^(id data, NSError *error) {
        [self loadMessage];
    }];
}

- (IBAction)tabAction:(id)sender {
    UIButton *button = (UIButton *)sender;
    self.currentTypeIndex = button.tag - 1;
    self.lineView.centerX = button.centerX;
    NSLog(@"%ld",(long)button.tag);
    if (button.tag == 0) {
        [self filterArr:nil];
    }else{
        [self filterArr:self.typeArr[button.tag - 1]];
    }
}

- (void)filterArr:(NSString *)type{
    [self.tableViewArr removeAllObjects];
    if (!type) {
        [self.tableViewArr addObjectsFromArray:self.arr];
        [self.tableView reloadData];
    }else{
        [self.arr enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([[obj objectForKey:@"type"] isEqualToString:type]) {
                [self.tableViewArr addObject:obj];
            }
        }];
        [self.tableView reloadData];
    }
}

#pragma mark - UITableViewDelegate and UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.tableViewArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 105;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DHS2_MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHS2_MessageCell forIndexPath:indexPath];
    [cell updateCell:self.tableViewArr[indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = self.tableViewArr[indexPath.row];
    [[DHNetAPIClient shareDHNetAPIClient] request_notifications_readWithParams:@{@"notification_id":[dic objectForKey:@"_id"]} andBlock:^(id data, NSError *error) {
        [self loadMessage];
    }];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSDictionary *dic = [self.tableViewArr objectAtIndex:indexPath.row];
        [[DHNetAPIClient shareDHNetAPIClient] request_user_notifications_deleteWithParams:@{@"notification_id":[dic objectForKey:@"_id"]} andBlock:^(id data, NSError *error) {
            [self loadMessage];
        }];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

#pragma mark - arr
- (NSMutableArray *)arr{
    if (!_arr) {
        _arr = [NSMutableArray array];
    }
    return _arr;
}

- (NSMutableArray *)tableViewArr{
    if (!_tableViewArr) {
        _tableViewArr = [NSMutableArray array];
    }
    return _tableViewArr;
}

- (NSArray *)typeArr{
    if (!_typeArr) {
        _typeArr = [NSArray array];
    }
    return _typeArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
